<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>JS03</title>
</head>

<body>
    <div>
        <button>添加新的div</button>
        <button>在选中div之前添加新的div</button>
        <button>删除选中div</button>
        <button>用新div替换选中div</button>
    </div>
    <div id="container"></div>

    <script>

        var $ = function (selector) {
            var arr = document.querySelectorAll(selector);
            if (arr.length > 1) {
                return arr;
            } else if (arr.length == 1) {
                return arr[0];
            } else {
                return arr;
            }
        };

        $('#container').i = 0;


        var createDiv = function (idx) {
            var newDiv = document.createElement('div');
            var style = {
                width: '50px',
                height: '50px',
                border: '1px solid #AA2222',
                margin: '5px',
                "font-size": "30px",
                textAlign: 'center',
                lineHeight: '50px',
                cursor: 'pointer'
            };

            for (var prop in style) {
                newDiv.style[prop] = style[prop];
            }

            //创建文本节点
            var txtNode = document.createTextNode(idx);
            newDiv.appendChild(txtNode);

            newDiv.onclick = function () {

                var divs = this.parentNode.childNodes;
                divs.forEach(function (emt) {
                    emt.style.backgroundColor = 'transparent';
                });

                this.style.backgroundColor = '#FFEEE0';
                this.parentNode.curr = this;//在容器上记录选中div
            };

            return newDiv;
        };

        $('button:first-child').onclick = function () {
            $('#container').appendChild(createDiv(++$('#container').i));

        };

        $('button:nth-child(2)').onclick = function () {
            if($('#container').curr){
                $('#container').insertBefore(createDiv(++$('#container').i),$('#container').curr);               
            }
        };

        $('button:nth-child(3)').onclick = function () {
            if($('#container').curr){
                $('#container').removeChild($('#container').curr);   
                $('#container').curr=undefined;          
            }
        };

        $('button:nth-child(4)').onclick = function () {
            if($('#container').curr){
                $('#container').replaceChild(createDiv(++$('#container').i),$('#container').curr);   
                $('#container').curr=undefined;          
            }
        };



    </script>



</body>


</html>